<?php
/**
 * 重载CDbConnection类
 * 扩展数据库主从配置
 */

class MCDbConnection extends CDbConnection
{
	public $db_config = array();
	//当前数据连接池类型
	public $current_conn_type = DB_CONN;
	//当前数据连接
	public $current_conn_idx = false;
	//连接失败的数据连接
	//public $error_conn_idx = false;
	
	public function __construct($t = false, $idx = false)
	{
		if ($t)
		{
			//标记当前数据连接池类型
			$this->current_conn_type = $t;
			$this->current_conn_idx = $idx;
		}
		$this->init();
	}
	
	public function init()
	{
		$this->connSelect();
		parent::init();
	}
	
	public final function setConnType($t)
	{
		$this->current_conn_type = $t;
	}
	
	public final function getConnType()
	{
		return $this->current_conn_type;
	}
	
	public final function setConnIdx($idx)
	{
		$this->current_conn_idx = $idx;
	}
	
	public final function getConnIdx()
	{
		return $this->current_conn_idx;
	}
	
	public static function getDbConnection($t = DB_CONN, $idx = false)
	{
		static $_instance = array();
		if ($idx === false)
		{
			if (isset($_instance[$t]))
			{
				$idx = array_rand($_instance[$t]);
				return $_instance[$t][$idx];
			}
		}
		else 
		{
			if (isset($_instance[$t][$idx])) {
				return $_instance[$t][$idx];
			}
		}
		$db = new self($t, $idx);
		$_instance[$t][$db->current_conn_idx] = $db;
		return $db;
	}
	
	/**
	 * 选择数据连接池
	 * @param string $t
	 * @throws CDbException
	 */
	public function connSelect($t = false, $idx = false)
	{
// 		if (!in_array($this->current_conn_type, array('write', 'read')))
// 		{
// 			throw new CDbException('数据库连接类型错误。');
// 		}
		if ($t)
		{
			$this->setConnType($t);
		}
		if ($idx)
		{
			$this->setConnIdx($idx);
		}
		
		//获取配置文件
		$_db_config = $this->getConfig();
		
		foreach ($_db_config as $property => $value)
		{
			$this->{$property} = $value;
		}
	}
	
	/**
	 * 重载open方法
	 * 数据库连接失败时尝试连接其它数据库连接
	 * @see CDbConnection::open()
	 */
	protected function open()
	{
		try
		{
			parent::open();
		}
		catch (CDbException $e)
		{
			if ($e->getCode() == 2002)
			{
				//标记连接失败的数据库
				//$this->error_conn_idx[$this->current_conn_type][] = $this->current_conn_idx;
				//删除连接失败的数据库连接
				unset($this->db_config[$this->current_conn_type][$this->current_conn_idx]);
				//重新初始化数据库连接
				$this->init();
			}
		}
	}
	
	protected function getConfig()
	{
		//获取配置文件
		if (empty($this->db_config))
		{
			$config = require PROTECTED_PATH . '/config/database.php';
			$this->db_config = $config['db_config'];
		}
		if ($this->current_conn_idx === false)
		{
			$this->current_conn_idx = array_rand($this->db_config[$this->current_conn_type]);
		}
		return $this->db_config[$this->current_conn_type][$this->current_conn_idx];
	}
}